package com.qianyu.helper;


import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import com.qianyu.entity.bean.User;
import com.qianyu.enumerate.ResultEnum;
import com.qianyu.exception.CustomerException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.util.ObjectUtils;

/**
 * 登录鉴权助手
 *
 * @Author: LJ
 * @Date: 2022/12/16
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class LoginHelper {
    public static final String LOGIN_USER_KEY = "loginUser";
    // 30天
    public static final Long REMEMBER_ME_TIME = 60 * 60 * 24 * 30L;
    // 6小时
    public static final Long NO_REMEMBER_ME_TIME = 60 * 60 * 6L;

    /**
     * 登录系统
     *
     * @param loginUser 登录用户信息
     */
    public static void login(User loginUser, boolean rememberMe) {
        SaHolder.getStorage().set(LOGIN_USER_KEY, loginUser);
        SaLoginModel loginModel = new SaLoginModel()
                .setTimeout(rememberMe ? REMEMBER_ME_TIME : NO_REMEMBER_ME_TIME);
        StpUtil.login(loginUser.getId(), loginModel);
        setLoginUser(loginUser);
    }

    /**
     * 设置用户数据(多级缓存)
     */
    public static void setLoginUser(User loginUser) {
        StpUtil.getTokenSession().set(LOGIN_USER_KEY, loginUser);
    }

    /**
     * 获取用户(多级缓存)
     */
    public static User getLoginUser() {
        User loginUser = (User) SaHolder.getStorage().get(LOGIN_USER_KEY);
        if (loginUser != null) {
            return loginUser;
        }
        loginUser = (User) StpUtil.getTokenSession().get(LOGIN_USER_KEY);
        SaHolder.getStorage().set(LOGIN_USER_KEY, loginUser);
        return loginUser;
    }

    /**
     * 获取用户id
     */
    public static Long getUserId() {
        User loginUser = getLoginUser();
        if (ObjectUtils.isEmpty(loginUser)) {
            Long loginId = StpUtil.getLoginIdAsLong();
            if (ObjectUtils.isEmpty(loginId)) {
                throw new CustomerException(ResultEnum.USER_ACCOUNT_DOES_NOT_EXIST);
            }
            // 用户id在总是在最后
            return loginId;
        }
        return loginUser.getId();
    }

    /**
     * 获取用户账户
     */
    public static String getUsername() {
        return getLoginUser().getUsername();
    }

}
